package com.module.ad_gromore.ad;


import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.module.ad_gromore.LogADUtils;
import com.module.ad_gromore.SplashAdListener;
import com.module.ad_gromore.manager.AdSplashManager;
import com.bytedance.msdk.adapter.util.UIUtils;
import com.bytedance.msdk.api.AdError;
import com.bytedance.msdk.api.v2.ad.splash.GMSplashAdListener;
import com.bytedance.msdk.api.v2.ad.splash.GMSplashAdLoadCallback;

public class SplashAd {
    private AdSplashManager mAdSplashManager;
    private final String TAG = "广告";
    private ViewGroup mSplashContainer;
    //强制加载兜底开屏广告，只能在GroMore提供的demo中使用，其他情况设置无效
    private boolean mForceLoadBottom = false;
    private SplashAdListener listener;
    private String mAdUnitId;
    private int width;
    private int height;
    private String appId;
    private String doudiId;//兜底Id
    private Handler handler = new Handler(Looper.getMainLooper());

    private static SplashAd splashAd;

    public static void loadAd(Activity context, String appId, final String mAdUnitId, String doudiId, SplashAdListener listener) {
        splashAd = new SplashAd(appId, mAdUnitId, doudiId, listener);
        splashAd.load(context);
        if (context instanceof FragmentActivity) {
            ((FragmentActivity) context).getLifecycle().addObserver(new DefaultLifecycleObserver() {
                @Override
                public void onDestroy(@NonNull LifecycleOwner owner) {
                    DefaultLifecycleObserver.super.onDestroy(owner);
                    if (splashAd != null) {
                        splashAd.onDestroy();
                        splashAd = null;
                    }
                    ((FragmentActivity) context).getLifecycle().removeObserver(this);
                }
            });
        }
    }

    private SplashAd(String appId, String mAdUnitId, String doudiId, SplashAdListener listener) {
        this.mAdUnitId = mAdUnitId;
        this.listener = listener;
        this.appId = appId;
        this.doudiId = doudiId;
        mSplashContainer = listener != null ? listener.getAdView() : null;
    }

    private void load(Activity context) {
        mAdSplashManager = new AdSplashManager(context, appId, doudiId, mForceLoadBottom, new GMSplashAdLoadCallback() {
            @Override
            public void onSplashAdLoadFail(AdError adError) {
                LogADUtils.d(TAG, adError.message);
                LogADUtils.e(TAG, "load splash ad error : " + adError.code + ", " + adError.message);
                // 获取本次waterfall加载中，加载失败的adn错误信息。
                if (mAdSplashManager.getSplashAd() != null)
                    LogADUtils.d(TAG, "ad load infos: " + mAdSplashManager.getSplashAd().getAdLoadInfoList());
                goToMainActivity();
            }

            @Override
            public void onSplashAdLoadSuccess() {
                LogADUtils.e(TAG, "load splash ad success ");
                mAdSplashManager.printInfo();
                // 根据需要选择调用isReady()
//                if (mAdSplashManager.getSplashAd().isReady()) {
//                    mAdSplashManager.getSplashAd().showAd(mSplashContainer);
//                }
                mAdSplashManager.getSplashAd().showAd(mSplashContainer);
                //由于可能存在显示试图，一只显示不出来，导致界面一直卡死，所以这边倒计时
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        goToMainActivity();
                    }
                }, 10000);

            }

            // 注意：***** 开屏广告加载超时回调已废弃，统一走onSplashAdLoadFail，GroMore作为聚合不存在SplashTimeout情况。*****
            @Override
            public void onAdLoadTimeout() {
                LogADUtils.e(TAG, "load splash ad timeout ");

            }
        }, mSplashAdListener);

        //加载开屏广告
        if (mAdSplashManager != null) {
            width = listener != null ? listener.getAdView().getWidth() : UIUtils.getScreenWidth(context);
            height = listener != null ? listener.getAdView().getHeight() : UIUtils.getScreenHeight(context);
            mAdSplashManager.loadSplashAd(mAdUnitId, width, height);
        }
    }

    private GMSplashAdListener mSplashAdListener = new GMSplashAdListener() {
        @Override
        public void onAdClicked() {
            LogADUtils.d(TAG, "onAdClicked");
        }

        @Override
        public void onAdShow() {
            LogADUtils.d(TAG, "onAdShow");
        }

        /**
         * show失败回调。如果show时发现无可用广告（比如广告过期），会触发该回调。
         * 开发者应该结合自己的广告加载、展示流程，在该回调里进行重新加载。
         * @param adError showFail的具体原因
         */
        @Override
        public void onAdShowFail(AdError adError) {
            LogADUtils.d(TAG, "onAdShowFail");
            // 开发者应该结合自己的广告加载、展示流程，在该回调里进行重新加载
            if (mAdSplashManager != null) {
                mAdSplashManager.loadSplashAd(mAdUnitId, width, height);
            }
        }

        @Override
        public void onAdSkip() {
            LogADUtils.d(TAG, "onAdSkip");
            goToMainActivity();
        }

        @Override
        public void onAdDismiss() {
            LogADUtils.d(TAG, "onAdDismiss");
            goToMainActivity();
        }
    };

    /**
     * 跳转到主页面
     */
    private void goToMainActivity() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (listener != null) {
            listener.goActivity();
        }
    }

    public void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (mSplashContainer != null) {
            mSplashContainer.removeAllViews();
        }
        if (mAdSplashManager != null) {
            mAdSplashManager.destroy();
        }
    }
}
